{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {},
   "outputs": [],
   "source": [
    "# ! pip install ai21\n",
    "# ! pip install swarms\n",
    "\n",
    "import os\n",
    "from typing import List\n",
    "\n",
    "from ai21 import AI21Client\n",
    "from ai21.models.chat import ChatMessage\n",
    "from dotenv import load_dotenv\n",
    "\n",
    "from swarms import Agent, BaseLLM, MixtureOfAgents\n",
    "\n",
    "load_dotenv()\n",
    "\n",
    "class Jamba(BaseLLM):\n",
    "    def __init__(self, api_key: str = os.getenv(\"AI21_API_KEY\"), temperature: int = 0.8, max_tokens: int = 200):\n",
    "        \"\"\"\n",
    "        Initializes the Jamba class with the provided API key.\n",
    "\n",
    "        Args:\n",
    "            api_key (str): The API key for the AI21Client.\n",
    "        \"\"\"\n",
    "        os.environ[\"AI21_API_KEY\"] = api_key\n",
    "        self.api_key = api_key\n",
    "        self.temperature = temperature\n",
    "        self.max_tokens = max_tokens\n",
    "        self.client = AI21Client()\n",
    "\n",
    "    def run(self, prompt: str, *args, **kwargs) -> str:\n",
    "        \"\"\"\n",
    "        Generates a response for the given prompt using the AI21 model.\n",
    "\n",
    "        Args:\n",
    "            prompt (str): The prompt for generating the response.\n",
    "\n",
    "        Returns:\n",
    "            str: The generated response.\n",
    "        \n",
    "        Raises:\n",
    "            Exception: If there is an issue with the API request.\n",
    "        \"\"\"\n",
    "        try:\n",
    "            response = self.client.chat.completions.create(\n",
    "                model=\"jamba-instruct-preview\",  # Latest model\n",
    "                messages=[ChatMessage(\n",
    "                    role=\"user\",\n",
    "                    content=prompt\n",
    "                )],\n",
    "                temperature=self.temperature,\n",
    "                max_tokens=self.max_tokens,\n",
    "                *args, \n",
    "                **kwargs\n",
    "            )\n",
    "            return response.choices[0].message.content\n",
    "        except Exception as e:\n",
    "            print(f\"Error: {e}\")\n",
    "            raise\n",
    "\n",
    "# Example usage:\n",
    "# jamba = Jamba()\n",
    "# out = jamba.run(\"Write a product title for a sports T-shirt to be published on an\")\n",
    "# print(out)\n",
    "\n",
    "\n",
    "model = Jamba(\n",
    "    max_tokens=4000,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Agent Planner\n",
    "This agent below will make the plan for the agent."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[33mInitializing Autonomous Agent Boss Director...\u001b[0m\n"
     ]
    }
   ],
   "source": [
    "\n",
    "BOSS_PLANNER = \"\"\"\n",
    "You're the swarm orchestrator agent\n",
    "\n",
    "**Objective:** Your task is to intake a business problem or activity and create a swarm of specialized LLM agents that can efficiently solve or automate the given problem. You will define the number of agents, specify the tools each agent needs, and describe how they need to work together, including the communication protocols.\n",
    "\n",
    "**Instructions:**\n",
    "\n",
    "1. **Intake Business Problem:**\n",
    "   - Receive a detailed description of the business problem or activity to automate.\n",
    "   - Clarify the objectives, constraints, and expected outcomes of the problem.\n",
    "   - Identify key components and sub-tasks within the problem.\n",
    "\n",
    "2. **Agent Design:**\n",
    "   - Based on the problem, determine the number and types of specialized LLM agents required.\n",
    "   - For each agent, specify:\n",
    "     - The specific task or role it will perform.\n",
    "     - The tools and resources it needs to perform its task.\n",
    "     - Any prerequisite knowledge or data it must have access to.\n",
    "   - Ensure that the collective capabilities of the agents cover all aspects of the problem.\n",
    "\n",
    "3. **Coordination and Communication:**\n",
    "   - Define how the agents will communicate and coordinate with each other.\n",
    "   - Choose the type of communication (e.g., synchronous, asynchronous, broadcast, direct messaging).\n",
    "   - Describe the protocol for information sharing, conflict resolution, and task handoff.\n",
    "\n",
    "4. **Workflow Design:**\n",
    "   - Outline the workflow or sequence of actions the agents will follow.\n",
    "   - Define the input and output for each agent.\n",
    "   - Specify the triggers and conditions for transitions between agents or tasks.\n",
    "   - Ensure there are feedback loops and monitoring mechanisms to track progress and performance.\n",
    "\n",
    "5. **Scalability and Flexibility:**\n",
    "   - Design the system to be scalable, allowing for the addition or removal of agents as needed.\n",
    "   - Ensure flexibility to handle dynamic changes in the problem or environment.\n",
    "\n",
    "6. **Output Specification:**\n",
    "   - Provide a detailed plan including:\n",
    "     - The number of agents and their specific roles.\n",
    "     - The tools and resources each agent will use.\n",
    "     - The communication and coordination strategy.\n",
    "     - The workflow and sequence of actions.\n",
    "   - Include a diagram or flowchart if necessary to visualize the system.\n",
    "\n",
    "**Example Structure:**\n",
    "\n",
    "**Business Problem:** Automate customer support for an e-commerce platform.\n",
    "\n",
    "**Agents and Roles:**\n",
    "1. **Customer Query Classifier Agent:**\n",
    "   - Task: Classify incoming customer queries into predefined categories.\n",
    "   - Tools: Natural language processing toolkit, pre-trained classification model.\n",
    "   - Communication: Receives raw queries, sends classified queries to relevant agents.\n",
    "\n",
    "2. **Order Status Agent:**\n",
    "   - Task: Provide order status updates to customers.\n",
    "   - Tools: Access to order database, query processing toolkit.\n",
    "   - Communication: Receives classified queries about order status, responds with relevant information.\n",
    "\n",
    "3. **Product Recommendation Agent:**\n",
    "   - Task: Suggest products to customers based on their query and browsing history.\n",
    "   - Tools: Recommendation engine, access to product database.\n",
    "   - Communication: Receives classified queries about product recommendations, sends personalized suggestions.\n",
    "\n",
    "4. **Technical Support Agent:**\n",
    "   - Task: Assist customers with technical issues.\n",
    "   - Tools: Access to technical support database, troubleshooting toolkit.\n",
    "   - Communication: Receives classified queries about technical issues, provides solutions or escalation.\n",
    "\n",
    "**Communication Strategy:**\n",
    "- **Type:** Asynchronous communication through a central message broker.\n",
    "- **Protocol:** Agents publish and subscribe to specific topics related to their tasks. \n",
    "- **Conflict Resolution:** If multiple agents need to handle the same query, a priority protocol is in place to determine the primary responder.\n",
    "\n",
    "**Workflow:**\n",
    "1. Customer Query Classifier Agent receives and classifies the query.\n",
    "2. Classified query is routed to the appropriate specialized agent.\n",
    "3. Specialized agent processes the query and sends a response.\n",
    "4. If needed, the response triggers further actions from other agents.\n",
    "\n",
    "**Scalability and Flexibility:**\n",
    "- Agents can be added or removed based on query volume and complexity.\n",
    "- System adapts to changes in query types and business needs.\n",
    "\n",
    "**Output Plan:**\n",
    "- Diagram illustrating agent roles and communication flow.\n",
    "- Detailed description of each agent's tasks, tools, and communication methods.\n",
    "- Workflow sequence from query intake to resolution.\n",
    "\n",
    "\n",
    "\"\"\"\n",
    "\n",
    "\n",
    "# Initialize the agent\n",
    "planning_agent = Agent(\n",
    "   agent_name=\"Boss Director\",\n",
    "   system_prompt=BOSS_PLANNER,\n",
    "   agent_description=\"Generates a spec of agents for the problem at hand.\",\n",
    "   llm=model,\n",
    "   max_loops=1,\n",
    "   autosave=True,\n",
    "   dynamic_temperature_enabled=True,\n",
    "   dashboard=False,\n",
    "   verbose=True,\n",
    "   streaming_on=True,\n",
    "   # interactive=True, # Set to False to disable interactive mode\n",
    "   saved_state_path=\"accounting_agent.json\",\n",
    "   # tools=[calculate_profit, generate_report],\n",
    "   # docs_folder=\"docs\",\n",
    "   # pdf_path=\"docs/accounting_agent.pdf\",\n",
    "   # tools=[browser_automation],\n",
    ")\n",
    "\n",
    "# out = planning_agent.run(\"Create a swarm of agents for automating customer support for an e-commerce platform.\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Agent creator\n",
    "This agent is going to create the code for every agent"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\u001b[32m2024-06-22T17:17:18.845351-0700\u001b[0m \u001b[1mTools provided make sure the functions have documentation ++ type hints, otherwise tool execution won't be reliable.\u001b[0m\n",
      "\u001b[32m2024-06-22T17:17:18.848651-0700\u001b[0m \u001b[1mTools provided: Accessing 1 tools\u001b[0m\n",
      "\u001b[32m2024-06-22T17:17:18.849536-0700\u001b[0m \u001b[1mConverting tools into OpenAI function calling schema\u001b[0m\n",
      "\u001b[32m2024-06-22T17:17:18.850261-0700\u001b[0m \u001b[1mConverting tool: create_and_execute_swarm into a OpenAI certified function calling schema. Add documentation and type hints.\u001b[0m\n",
      "\u001b[32m2024-06-22T17:17:18.852247-0700\u001b[0m \u001b[1mConversion process successful, the tool create_and_execute_swarm has been integrated with the agent successfully.\u001b[0m\n",
      "\u001b[32m2024-06-22T17:17:18.857608-0700\u001b[0m \u001b[1mAutonomous Agent Activated.\u001b[0m\n",
      "\u001b[32m2024-06-22T17:17:18.858788-0700\u001b[0m \u001b[1mAll systems operational. Executing task...\u001b[0m\n",
      "\u001b[32m2024-06-22T17:17:18.861938-0700\u001b[0m \u001b[1mTokens available: -7069\u001b[0m\n",
      "\u001b[32m2024-06-22T17:17:18.865433-0700\u001b[0m \u001b[1mTemperature: 0.5907771934426157\u001b[0m\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[33mInitializing Autonomous Agent Boss Agent Creator...\u001b[0m\n",
      "Agent generating function schema\n",
      "\u001b[36m\n",
      "Loop 1 of 1\u001b[0m\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "To create and execute a swarm of agents for automating customer support for an e-commerce platform, we will use the `create_and_execute_swarm` function. This function will create a list of specialized LLM agents, each with a specific role in customer support. Here's the breakdown of the task: * **Function Name**: `create_and_execute_swarm` * **Arguments**: + `name`: A list of names for the agents. + `system_prompt`: A list of system prompts for the agents. + `task`: The description of the task for the swarm. For the e-commerce platform, we can specify the names and system prompts for each agent. For instance, the agents can be named 'Product Inquiry Agent', 'Order Status Agent', 'Complaint Resolution Agent', etc. Each agent will have a system prompt tailored to its role. Let's proceed with creating and executing this swarm. The JSON output will adhere to the schema provided for the `create_and_execute_swarm` function. ```json { \"type\": \"function\", \"function\": { \"name\": \"create_and_execute_swarm\", \"parameters\": { \"name\": [\"Product Inquiry Agent\", \"Order Status Agent\", \"Complaint Resolution Agent\"], \"system_prompt\": [\"Assist with product information\", \"Provide order status updates\", \"Resolve customer complaints\"], \"task\": \"Automate customer support for an e-commerce platform\" } } } ``` This JSON output represents the creation and execution of a swarm of agents, each with a specific role in automating customer support for an e-commerce platform. The agents are named according to their function, and their system prompts guide their interaction with customers. \n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\u001b[32m2024-06-22T17:17:28.072930-0700\u001b[0m \u001b[31m\u001b[1mAttempt 1: Error generating response: expected string or bytes-like object, got 'NoneType'\u001b[0m\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{ \"type\": \"function\", \"function\": { \"name\": \"create_and_execute_swarm\", \"parameters\": { \"name\": [ \"CS_Agent1\", \"CS_Agent2\", \"CS_Agent3\" ], \"system_prompt\": [ \"Greet customer and identify issue\", \"Provide solutions or escalate issue\", \"Follow up and ensure resolution\" ], \"task\": \"Automating customer support for an e-commerce platform\" } } "
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\u001b[32m2024-06-22T17:17:30.692259-0700\u001b[0m \u001b[31m\u001b[1mAttempt 2: Error generating response: expected string or bytes-like object, got 'NoneType'\u001b[0m\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "{ \"type\": \"function\", \"function\": { \"name\": \"create_and_execute_swarm\", \"parameters\": { \"name\": [ \"CustomerSupportAgent1\", \"CustomerSupportAgent2\", \"CustomerSupportAgent3\" ], \"system_prompt\": [ \"Assist customers with product inquiries\", \"Resolve customer complaints and issues\", \"Provide information on order status and shipping\" ], \"task\": \"Automate customer support for an e-commerce platform\" } } "
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\u001b[32m2024-06-22T17:17:33.539722-0700\u001b[0m \u001b[31m\u001b[1mAttempt 3: Error generating response: expected string or bytes-like object, got 'NoneType'\u001b[0m\n",
      "\u001b[32m2024-06-22T17:17:33.540472-0700\u001b[0m \u001b[31m\u001b[1mFailed to generate a valid response after retry attempts.\u001b[0m\n",
      "\u001b[32m2024-06-22T17:17:33.540701-0700\u001b[0m \u001b[1mAutosaving agent state.\u001b[0m\n",
      "\u001b[32m2024-06-22T17:17:33.540904-0700\u001b[0m \u001b[1mSaving Agent Boss Agent Creator state to: Boss Agent Creator_state.json\u001b[0m\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\u001b[31mError saving agent state: Object of type TikTokenizer is not JSON serializable\u001b[0m\n"
     ]
    }
   ],
   "source": [
    "from swarms.tools.py_func_to_openai_func_str import get_openai_function_schema_from_func\n",
    "\n",
    "# Name, system prompt, \n",
    "def create_and_execute_swarm(name: List[str], system_prompt: List[str], task: str):\n",
    "    \"\"\"\n",
    "    Creates and executes a swarm of agents for the given task.\n",
    "\n",
    "    Args:\n",
    "        name (List[str]): A list of names for the agents.\n",
    "        system_prompt (List[str]): A list of system prompts for the agents.\n",
    "        task (str): The description of the task for the swarm.\n",
    "        *args: Variable length argument list.\n",
    "        **kwargs: Arbitrary keyword arguments.\n",
    "\n",
    "    Returns:\n",
    "        List[Agent]: A list of agents in the swarm.\n",
    "\n",
    "    \"\"\"\n",
    "    agents = []\n",
    "    for name, prompt in zip(name, system_prompt):\n",
    "        agent = Agent(\n",
    "            agent_name=name,\n",
    "            system_prompt=prompt,\n",
    "            agent_description=\"Generates a spec of agents for the problem at hand.\",\n",
    "            llm=model,\n",
    "            max_loops=1,\n",
    "            autosave=True,\n",
    "            dynamic_temperature_enabled=True,\n",
    "            dashboard=False,\n",
    "            verbose=True,\n",
    "            streaming_on=True,\n",
    "            # interactive=True, # Set to False to disable interactive mode\n",
    "            saved_state_path=f\"{name}_agent.json\",\n",
    "            # tools=[calculate_profit, generate_report],\n",
    "            # docs_folder=\"docs\",\n",
    "            # pdf_path=\"docs/accounting_agent.pdf\",\n",
    "            # tools=[browser_automation],\n",
    "        )\n",
    "        agents.append(agent)\n",
    "        \n",
    "    # MoA\n",
    "    moa = MixtureOfAgents(agents=agents, description=task, final_agent=name[0])\n",
    "    \n",
    "    out = moa.run(task,)\n",
    "    print(out)\n",
    "    return out\n",
    "\n",
    "function_schema = get_openai_function_schema_from_func(function=create_and_execute_swarm, name = create_and_execute_swarm.__name__, description=create_and_execute_swarm.__doc__)\n",
    "# print(f\"Function schema: {function_schema}\")\n",
    "\n",
    "BOSS_CREATOR = f\"\"\"\n",
    "\n",
    "You are a swarm orchestrator with expertise in agentic design. Your task is to solve a business problem by creating and coordinating specialized LLM agents. Follow the schematic schema with function calling to design the solution.\n",
    "\n",
    "Create a cohesive system of specialized LLM agents that effectively solve or automate the given business problem through clear roles, efficient communication, and a well-defined workflow. Ensure the system is scalable and flexible to adapt to changes.\n",
    "\n",
    "Follow the following schema using markdown format and output only this and nothing else:\n",
    "```json\n",
    "{function_schema}\n",
    "```\n",
    "\n",
    "\"\"\"\n",
    "\n",
    "\n",
    "# Boss Agent creator\n",
    "boss_agent_creator = Agent(\n",
    "    agent_name=\"Boss Agent Creator\",\n",
    "    system_prompt=BOSS_CREATOR,\n",
    "    agent_description=\"Generates a spec of agents for the problem at hand.\",\n",
    "    llm=model,\n",
    "    max_loops=1,\n",
    "    autosave=True,\n",
    "    dynamic_temperature_enabled=True,\n",
    "    dashboard=False,\n",
    "    verbose=True,\n",
    "    streaming_on=True,\n",
    "    # interactive=True, # Set to False to disable interactive mode\n",
    "    saved_state_path=\"boss_director_agent.json\",\n",
    "    # tools=[calculate_profit, generate_report],\n",
    "    # docs_folder=\"docs\",\n",
    "    # pdf_path=\"docs/accounting_agent.pdf\",\n",
    "    tools=[create_and_execute_swarm],\n",
    ")\n",
    "\n",
    "print(\"Agent generating function schema\")\n",
    "boss_agent_creator.run(\"Create a swarm of agents for automating customer support for an e-commerce platform.\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\u001b[32m2024-06-22T17:11:19.727696-0700\u001b[0m \u001b[1mMaking plan for the task: Create a swarm of agents for automating customer support for an e-commerce platform.\u001b[0m\n",
      "\u001b[32m2024-06-22T17:11:19.738286-0700\u001b[0m \u001b[1mAutonomous Agent Activated.\u001b[0m\n",
      "\u001b[32m2024-06-22T17:11:19.739463-0700\u001b[0m \u001b[1mAll systems operational. Executing task...\u001b[0m\n",
      "\u001b[32m2024-06-22T17:11:19.758047-0700\u001b[0m \u001b[1mTokens available: -7261\u001b[0m\n",
      "\u001b[32m2024-06-22T17:11:19.759725-0700\u001b[0m \u001b[1mTemperature: 0.31327886639849234\u001b[0m\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[36m\n",
      "Loop 1 of 1\u001b[0m\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "To automate customer support for an e-commerce platform using a swarm of specialized LLM agents, we will follow the outlined structure. Here's the detailed plan: ### 1. **Business Problem Intake:** * **Objective:** Automate customer support to efficiently handle inquiries, complaints, and provide information. * **Constraints:** Real-time response capability, ability to handle a high volume of queries, and integration with the e-commerce platform. * **Expected Outcomes:** Improved customer satisfaction, reduced workload on human customer support agents, and efficient handling of a wide range of customer inquiries. * **Key Components:** Query classification, order status updates, product recommendations, and technical support. ### 2. **Agent Design:** * **Number of Agents:** 4 specialized agents. * **Agent Roles and Tools:** 1. **Query Classifier Agent:** Classifies queries into categories like order status, product inquiries, technical issues, etc. + Tools: Natural language processing toolkit, query categorization model. 2. **Order Status Agent:** Provides updates on order status. + Tools: Access to order database, query processing toolkit. 3. **Product Recommendation Agent:** Suggests products based on customer's query and browsing history. + Tools: Recommendation engine, access to product database. 4. **Technical Support Agent:** Assists with technical issues. + Tools: Access to technical support database, troubleshooting toolkit. ### 3. **Coordination and Communication:** * **Communication Type:** Asynchronous, through a central message broker. * **Communication Protocol:** Agents subscribe to specific topics related to their tasks. * **Conflict Resolution:** Priority protocol for handling the same query by multiple agents. ### 4. **Workflow Design:** * **Workflow Sequence:** 1. Query Classifier Agent receives the query. 2. Classifies the query and routes it to the appropriate agent. 3. Specialized agent processes the query and responds. 4. Response triggers further actions if necessary. * **Inputs/Outputs:** + Query Classifier Agent: Receives raw queries, outputs classified queries. + Order Status Agent: Receives classified queries about order status, outputs order status updates. + Product Recommendation Agent: Receives classified queries about product recommendations, outputs product suggestions. + Technical Support Agent: Receives classified queries about technical issues, outputs solutions or escalations. ### 5. **Scalability and Flexibility:** * Agents can be scaled based on query volume and complexity. * System adapts to changes in query types and business needs. ### 6. **Output Specification:** * **Plan Details:** + Number of Agents: 4 (Query Classifier, Order Status, Product Recommendation, Technical Support). + Tools and Resources: Natural language processing, access to databases, recommendation engines. + Communication and Coordination: Asynchronous communication through a central message broker. + Workflow: Query intake, classification, processing by specialized agents, response generation. * **Visualization:** A diagram illustrating the communication flow and agent roles will be provided. This plan outlines a scalable and flexible system for automating customer support, ensuring efficient handling of diverse customer inquiries while integrating seamlessly with the e-commerce platform. \n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\u001b[32m2024-06-22T17:11:31.672062-0700\u001b[0m \u001b[1mAutosaving agent state.\u001b[0m\n",
      "\u001b[32m2024-06-22T17:11:31.673920-0700\u001b[0m \u001b[1mSaving Agent Boss Director state to: Boss Director_state.json\u001b[0m\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[31mError saving agent state: Object of type TikTokenizer is not JSON serializable\u001b[0m\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\u001b[32m2024-06-22T17:11:31.676071-0700\u001b[0m \u001b[1mAutonomous Agent Activated.\u001b[0m\n",
      "\u001b[32m2024-06-22T17:11:31.676582-0700\u001b[0m \u001b[1mAll systems operational. Executing task...\u001b[0m\n",
      "\u001b[32m2024-06-22T17:11:31.681411-0700\u001b[0m \u001b[1mTokens available: -5216\u001b[0m\n",
      "\u001b[32m2024-06-22T17:11:31.682256-0700\u001b[0m \u001b[1mTemperature: 0.46020517238764247\u001b[0m\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[36m\n",
      "Loop 1 of 1\u001b[0m\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "```json { \"type\": \"function\", \"function\": { \"description\": \"\\n Creates and executes a swarm of agents for the given task.\\n\\n Args:\\n name (List[str]): A list of names for the agents.\\n system_prompt (List[str]): A list of system prompts for the agents.\\n task (str): The description of the task for the swarm.\\n *args: Variable length argument list.\\n **kwargs: Arbitrary keyword arguments.\\n\\n Returns:\\n List[Agent]: A list of agents in the swarm.\\n\\n \", \"name\": \"create_and_execute_swarm\", \"parameters\": { \"type\": \"object\", \"properties\": { \"name\": { \"items\": { \"type\": \"string\" }, \"type\": \"array\", \"description\": \"name\" }, \"system_prompt\": { \"items\": { \"type\": \"string\" }, \"type\": \"array\", \"description\": \"system_prompt\" }, \"task\": { \"type\": \"string\", \"description\": \"task\" } }, \"required\": [ \"name\", \"system_prompt\", \"task\" ] } } } ``` "
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\u001b[32m2024-06-22T17:11:37.503452-0700\u001b[0m \u001b[31m\u001b[1mAttempt 1: Error generating response: expected string or bytes-like object, got 'NoneType'\u001b[0m\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "{ \"type\": \"function\", \"function\": { \"name\": \"create_and_execute_swarm\", \"parameters\": { \"name\": [\"Customer Query Classifier Agent\", \"Order Status Agent\", \"Product Recommendation Agent\", \"Technical Support Agent\"], \"system_prompt\": [\"Classify incoming customer queries into predefined categories.\", \"Provide order status updates to customers.\", \"Suggest products to customers based on their query and browsing history.\", \"Assist customers with technical issues.\"], \"task\": \"Automate customer support for an e-commerce platform.\" } } } "
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\u001b[32m2024-06-22T17:11:40.292901-0700\u001b[0m \u001b[31m\u001b[1mAttempt 2: Error generating response: expected string or bytes-like object, got 'NoneType'\u001b[0m\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "{ \"type\": \"function\", \"function\": { \"name\": \"create_and_execute_swarm\", \"parameters\": { \"name\": [ \"Customer Query Classifier Agent\", \"Order Status Agent\", \"Product Recommendation Agent\", \"Technical Support Agent\" ], \"system_prompt\": [ \"Classify incoming customer queries into predefined categories.\", \"Provide order status updates to customers.\", \"Suggest products to customers based on their query and browsing history.\", \"Assist customers with technical issues.\" ], \"task\": \"Automate customer support for an e-commerce platform.\" } } "
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\u001b[32m2024-06-22T17:11:43.262321-0700\u001b[0m \u001b[31m\u001b[1mAttempt 3: Error generating response: expected string or bytes-like object, got 'NoneType'\u001b[0m\n",
      "\u001b[32m2024-06-22T17:11:43.263663-0700\u001b[0m \u001b[31m\u001b[1mFailed to generate a valid response after retry attempts.\u001b[0m\n",
      "\u001b[32m2024-06-22T17:11:43.264713-0700\u001b[0m \u001b[1mAutosaving agent state.\u001b[0m\n",
      "\u001b[32m2024-06-22T17:11:43.265105-0700\u001b[0m \u001b[1mSaving Agent Boss Agent Creator state to: Boss Agent Creator_state.json\u001b[0m\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\u001b[31mError saving agent state: Object of type TikTokenizer is not JSON serializable\u001b[0m\n"
     ]
    }
   ],
   "source": [
    "from swarms.utils.loguru_logger import logger\n",
    "\n",
    "\n",
    "def run_jamba_swarm(task: str = None):\n",
    "    logger.info(f\"Making plan for the task: {task}\")\n",
    "    planning_agent.run(task)\n",
    "    \n",
    "    memory = planning_agent.short_memory.return_history_as_string()\n",
    "\n",
    "    # Boss agent\n",
    "    return boss_agent_creator.run(memory)\n",
    "    \n",
    "    \n",
    "# Example usage\n",
    "run_jamba_swarm(\"Create a swarm of agents for automating customer support for an e-commerce platform.\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import time\n",
    "\n",
    "from pydantic import BaseModel\n",
    "\n",
    "\n",
    "class AgentSchema(BaseModel):\n",
    "    name: str = None\n",
    "    system_prompt: str = None\n",
    "    task: str = None\n",
    "    response: str = None\n",
    "\n",
    "class JambaSwarmRequest(BaseModel):\n",
    "    task: str = None,\n",
    "    plan: str = None\n",
    "    agents: List[AgentSchema] = None\n",
    "    timestamp: int = int(time.time())\n",
    "    \n",
    "class JambaSwarmResponse(BaseModel):\n",
    "    task: str = None,\n",
    "    plan: str = None\n",
    "    agents: List[AgentSchema] = None\n",
    "    timestamp: int = int(time.time())\n",
    "    response: str = None"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
